<script setup lang="ts">
import type { FormInstance } from '@arco-design/web-vue'
import { Message } from '@arco-design/web-vue'
import AvatarUpload from './components/AvatarUpload.vue'
import { useDictLabel, useForm } from '@/hooks'
import { StudentApi } from '@/apis'
import type { TableInstanceColumns } from '@/components/ProTable/type'
import { calculateStudentGradeLimit } from '@/utils/edu'

const emit = defineEmits(['ok'])

const visible = ref(false)
const stuFormRef = ref<FormInstance>()

const rules: FormInstance['rules'] = {
  name: [{ required: true, message: '请输入学生姓名' }],
  gender: [{ required: true, message: '请选择学生性别' }],
  parentName: [{ required: true, message: '请输入家长姓名' }],
  parentPhone: [{ required: true, message: '请输入家长手机号' }],
}

const { form, resetForm } = useForm({
  name: '',
  parentId: '',
  parentPhone: '',
  parentName: undefined,
  parentRelation: undefined,
  source: undefined,
  gender: undefined,
  birthdate: undefined,
  avatar: undefined,
  admissionYear: undefined,
  fulltimeSchool: undefined,
  enrollStatus: '0',
  remark: undefined,
  permissions: [],
})

interface PermissionEx extends StudentApi.Permission {
  isEdit: boolean
  flag: boolean
}

const tableData = reactive<PermissionEx[]>([{
  isEdit: true,
  flag: false,
  subject: '',
  classLevel: 0,
  admissionYear: 0,
  classTypeId: '',
}])

const columns: TableInstanceColumns[] = [
  { title: '科目', slotName: 'subject', dataIndex: 'subject', width: 140 },
  { title: '年份', dataIndex: 'admissionYear', slotName: 'date', width: 140 },
  { title: '班级等级', dataIndex: 'classLevel', width: 140, slotName: 'classType' },
  { title: '注释', dataIndex: 'remark', slotName: 'remark', width: 340, ellipsis: true, tooltip: true },
  {
    title: '操作',
    slotName: 'action',
    width: 140,
    align: 'center',
    fixed: 'right',
  },
]

const updateLoading = ref(false)

const permissions = ref<StudentApi.Permission[]>([])

const operate = async (record, rowIndex) => {
  if (!record.isEdit) {
    record.isEdit = true
  } else {
    try {
      updateLoading.value = true
      if (record.flag) { // 修改
        permissions.value.push(record)
      } else { // 新增
        permissions.value[rowIndex] = record
        record.flag = true
      }
      record.isEdit = false
      Message.success('添加成功')
    } finally {
      updateLoading.value = false
    }
  }
}

// 新增
const onAdd = () => {
  console.log(tableData)
  if (tableData.length === 0 || !tableData[tableData.length - 1].isEdit) {
    tableData.push({
      isEdit: true,
      flag: false,
      subject: '',
      classLevel: 0,
      admissionYear: 0,
      classTypeId: '',
    })
  } else {
    Message.warning('请先保存上一条数据')
  }
}

const onClassTypeSelect = (item, record) => {
  if (!item?.level) {
    nextTick(() => {
      record.classLevel = undefined
    })
  } else {
    record.classLevel = item.level
  }
}

// 删除
const onDelete = (item, rowIndex) => {
  if (item && permissions.value.length === tableData.length) {
    permissions.value.splice(rowIndex, 1)
    tableData.splice(rowIndex, 1)
  } else {
    permissions.value.splice(rowIndex - 1, 1)
    tableData.splice(rowIndex, 1)
  }
}

const beforeOk = async () => {
  const isInvalid = await stuFormRef.value?.validate()
  if (isInvalid) {
    return
  }
  try {
    form.permissions = permissions.value
    await StudentApi.createStudent(form)
    Message.success('添加成功')
    return true
  // eslint-disable-next-line unused-imports/no-unused-vars
  } catch (_) {
    return false
  }
}

const handleOk = async () => {
  emit('ok')
}

const handleCancel = () => {
  visible.value = false
}

const reset = () => {
  stuFormRef.value?.resetFields()
  resetForm()
}

const open = () => {
  reset()
  visible.value = true
}

defineExpose({ open })
</script>

<template>
  <a-modal v-model:visible="visible" width="960px" :on-before-ok="beforeOk" @ok="handleOk" @cancel="handleCancel">
    <template #title>
      添加学员
    </template>
    <a-form ref="stuFormRef" :model="form" :rules="rules" layout="vertical">
      <div class="content">
        <div class="grid-item">
          <a-form-item label="姓名" field="name">
            <a-input v-model.trim="form.name" placeholder="请输入姓名" />
          </a-form-item>
        </div>
        <div class="grid-item">
          <a-form-item label="性别" field="gender">
            <DictSelect v-model="form.gender" type="radio" code="GenderEnum" />
          </a-form-item>
        </div>
        <div class="grid-item-large">
          <a-form-item label="头像" field="avatar">
            <AvatarUpload v-model="form.avatar" />
          </a-form-item>
        </div>
        <div class="grid-item">
          <a-form-item label="家长姓名" field="parentName">
            <a-input v-model.trim="form.parentName" placeholder="请输入家长姓名" />
          </a-form-item>
        </div>
        <div class="grid-item">
          <a-form-item label="家长手机" field="parentPhone">
            <a-input v-model.trim="form.parentPhone" placeholder="请输入家长手机" :max-length="11" />
          </a-form-item>
        </div>
        <div class="grid-item">
          <a-form-item label="家长关系" field="parentRelation">
            <DictSelect v-model="form.parentRelation" code="ParentRelation" placeholder="请选择家长关系" />
          </a-form-item>
        </div>
        <div class="grid-item">
          <a-form-item label="招生来源" field="source">
            <DictSelect v-model="form.source" code="StudentSource" placeholder="请选择招生来源" />
          </a-form-item>
        </div>
        <div class="grid-item">
          <a-form-item label="出生日期" field="birthdate">
            <a-date-picker v-model="form.birthdate" placeholder="请选择出生日期" />
          </a-form-item>
        </div>
        <div class="grid-item">
          <a-form-item label="入学年份（小学）" field="admissionYear">
            <a-year-picker v-model="form.admissionYear" placeholder="请选择入学年份" />
          </a-form-item>
        </div>
        <div class="grid-item">
          <a-form-item label="就读学校" field="fulltimeSchool">
            <a-input v-model.trim="form.fulltimeSchool" placeholder="请输入就读学校" />
          </a-form-item>
        </div>
      </div>
    </a-form>
    <ProTable
      :data="tableData" :columns="columns"
    >
      <template #toolbar-left>
        <a-button v-permission="['edu:student:manage']" type="primary" size="small" @click="onAdd">
          <icon-plus />
          新增权限
        </a-button>
      </template>
      <template #index="{ record }">
        <span>
          {{ record.sequence }}
        </span>
      </template>
      <template #subject="{ record }">
        <DictSelect v-if="record.isEdit" v-model="record.subject" placeholder="请选择科目" code="Subject" />
        <!-- <a-select v-if="record.isEdit" v-model="record.subject" placeholder="请选择科目" :options="basedict.subjects" /> -->
        <span v-else>{{ useDictLabel('Subject', record.subject) }}</span>
      </template>
      <template #date="{ record }">
        <a-year-picker v-if="record.isEdit" v-model="record.admissionYear" placeholder="请选择年份" />
        <span v-else>{{ record.admissionYear ? record.admissionYear.split('-')[0] : '' || '-' }}</span>
      </template>
      <template #classType="{ record }">
        <ClassTypeSelect v-if="record.isEdit" @select="onClassTypeSelect($event, record)" />
        <span v-else>{{ record.classLevel }}</span>
      </template>
      <template #remark="{ record }">
        <div style="font-size: 13px">
          <span>允许报名班级等级</span>
          <span class="font-600">&lt;={{ record.classLevel }}</span>
          <span>的</span>
          <span class="font-600">{{ calculateStudentGradeLimit(record.admissionYear) }}{{ useDictLabel('Subject', record.subject) }}</span>
          <span>班级</span>
        </div>
      </template>
      <template #action="{ record, rowIndex }">
        <a-space>
          <a-link v-permission="['edu:student:manage']" :loading="updateLoading" @click="operate(record, rowIndex)">
            {{ record.isEdit ? '保存' : '编辑' }}
          </a-link>
          <a-link v-permission="['edu:student:manage']" @click="onDelete(record, rowIndex)">
            删除
          </a-link>
        </a-space>
      </template>
    </ProTable>
  </a-modal>
</template>

<style lang="less" scoped>
.content {
  display: grid;
  grid-template-rows: repeat(3, 1fr);
  grid-template-columns: repeat(3, 1fr);
  column-gap: 60px;

  .grid-item-large {
    grid-row: span 2;
  }
}
</style>
